package com.sumfun.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.builders.*;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.service.ParameterType;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.oas.annotations.EnableOpenApi;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger3配置类
 * 用于生成RESTful API的接口文档
 * 配置了全局token认证参数
 *
 * @author Eric
 * @date 2023-07-30 22:17
 */

@Configuration
@EnableOpenApi
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //扫描指定包下的接口
                .apis(RequestHandlerSelectors.basePackage("com.sumfun.blog.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(globalOperation());  
    }

    private List<RequestParameter> globalOperation(){
        //添加head参数配置start
        List<RequestParameter> pars = new ArrayList<>();
        //配置token请求头
        RequestParameter tokenParameter = new RequestParameterBuilder()
                .name("token")
                .description("用户登录令牌")
                .required(false)
                .in(ParameterType.HEADER)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .build();
        pars.add(tokenParameter);
        return pars;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SumFun博客API文档")
                .description("SumFun博客接口文档")
                .contact(new Contact("sumfun", "http://sumfun.top", "sumfun@example.com"))
                .version("1.0")
                .build();
    }
}

